package guggaTests.tasks
{
	import flash.events.Event;
	
	import flexunit.framework.TestCase;
	
	import gugga.tasks.AnonymousTask;
	import gugga.tasks.FictiveTask;
	import gugga.tasks.FrameWaitingTask;
	import gugga.tasks.ITask;
	import gugga.tasks.events.TaskEvent;

	public class AnonymousTaskTest extends TestCase
	{
		private var mIsTaskRunning : Boolean = false;
		
		public function AnonymousTaskTest(methodName:String=null)
		{
			super(methodName);
		}
		
		public function testStartCompleteWithFrameWaitingTask() : void
		{
			var anonymousTask : AnonymousTask = new AnonymousTask(taskConstructor, [new FrameWaitingTask(5)], this);
			
			anonymousTask.addEventListener(TaskEvent.START, addAsync(assertAnonymousTaskStarted, 100));
			anonymousTask.addEventListener(TaskEvent.COMPLETED, addAsync(assertAnonymousTaskCompleted, 1000));
						
			anonymousTask.start();
		}
		
		public function testStartCompleteWithFictiveTask() : void
		{
			var anonymousTask : AnonymousTask = new AnonymousTask(taskConstructor, [new FictiveTask()], this);
			
			anonymousTask.addEventListener(TaskEvent.START, onAnonymousTaskStart);
			anonymousTask.addEventListener(TaskEvent.COMPLETED, addAsync(assertAnonymousTaskCompleted, 1000));
			
			anonymousTask.start();			
			assertTrue("AnonymousTask should be running", mIsTaskRunning);
		}
		
		public function testStartInterruptWithFrameWaitingTask() : void
		{
			var anonymousTask : AnonymousTask = new AnonymousTask(taskConstructor, [new FrameWaitingTask(5)]);
			
			anonymousTask.addEventListener(TaskEvent.START, onAnonymousTaskStart);
			anonymousTask.addEventListener(TaskEvent.INTERRUPTED, onAnonymousTaskInterrupted);
			
			anonymousTask.start();
			assertTrue("AnonymousTask should be running", mIsTaskRunning);
						
			anonymousTask.interrupt();
			assertFalse("AnonymousTask should not be running", mIsTaskRunning);
		}
		
		private function assertAnonymousTaskStarted(aEvent : TaskEvent) : void
		{				
			var anonymousTask : ITask = ITask(aEvent.target);
			
			assertTrue("AnonymousTask should be running", anonymousTask.isRunning());			
		}
		
		private function assertAnonymousTaskInterrupted(aEvent : TaskEvent) : void
		{			
			var anonymousTask : ITask = ITask(aEvent.target);
			
			assertFalse("AnonymousTask should be running", anonymousTask.isRunning());
		}
		
		private function assertAnonymousTaskCompleted(aEvent : TaskEvent) : void
		{
			var anonymousTask : ITask = ITask(aEvent.target);
			
			assertFalse("AnonymousTask should not be running", anonymousTask.isRunning());
		}
		
		private function onAnonymousTaskStart(aEvent : TaskEvent) : void
		{
			mIsTaskRunning = true;	
		}
		
		private function onAnonymousTaskInterrupted(aEvent : TaskEvent) : void
		{
			mIsTaskRunning = false;	
		}
		
		private function taskConstructor(aTask : ITask) : ITask
		{
			return aTask;
		}		
	}
}